new Vue({
    el: '#app',
    data() {
        return {
            list: [],
            pageSupply: null,
            stagedPayments: [],
            // 入口/权限相关标记
            enterpriseId: '',
            fromApplyDetail: false,
            currentSupplyId: '',
        };
    },
    mounted() {
        this.getDetails();
    },
    methods: {
        handleBack() {
            let fromPage = '';
            try { fromPage = getQueryObject(window.location.href, 'fromPage') || ''; } catch (e) { fromPage = ''; }
            const ref = document.referrer || '';
            if (fromPage === 'sales_order') { window.location.href = '../sales_order/index.html'; return; }
            if (fromPage === 'supply_order') { window.location.href = '../supply_order/index.html'; return; }
            if (ref.indexOf('/transaction/sales_order/index.html') !== -1) { window.location.href = '../sales_order/index.html'; return; }
            if (ref.indexOf('/transaction/supply_order/index.html') !== -1) { window.location.href = '../supply_order/index.html'; return; }
            window.location.href = './index.html';
        },
        formatStatus(status) {
            switch (String(status)) {
                case '0': return '待审核';
                case '2': return '通过';
                case '3': return '拒绝';
                default: return '未知';
            }
        },
        statusTagType(status) {
            switch (String(status)) {
                case '0': return 'warning';
                case '2': return 'success';
                case '3': return 'danger';
                default: return 'info';
            }
        },
        // 格式化拒绝记录文案（若后续展示 examineLogs）
        formatRejectLog(log, idx) {
            const reason = (log && log.Reason) ? log.Reason : '';
            const time = (log && (log.Create_Date || log.Operation_Datetime)) ? `（${log.Create_Date || log.Operation_Datetime}）` : '';
            return `${idx + 1}. ${reason}${time}`;
        },
        formatSupplyAddress(s) {
            if (!s) return '';
            const p = s.ProvinceNumber || '';
            const c = s.CityNumber || '';
            const d = s.CountyNumber || '';
            const a = s.Detailed_Address || '';
            return `${p}${c}${d}${a}`;
        },
        async getDetails() {
            const applyId = (function () {
                try { return getQueryObject(window.location.href, 'applyId') || ''; } catch (e) { return ''; }
            })();
            const fromPage = (function () {
                try { return getQueryObject(window.location.href, 'fromPage') || ''; } catch (e) { return ''; }
            })();
            // 记录来源：从销售订单入口（携带 applyId）进入时才显示操作按钮
            this.fromApplyDetail = (fromPage === 'sales_order');
            // 记录当前企业（用于权限或展示）
            try { this.enterpriseId = $.cookie('enterprise') || ''; } catch (e) { this.enterpriseId = ''; }
            if (!applyId) {
                this.$message && this.$message.warning && this.$message.warning('缺少申请单号参数 applyId');
            }

            try {
                // 1) 仅查询该申请单号的订单数据
                const orderRes = await httpRequest({
                    url: '/generalBusiness/generalQueryByTableName',
                    data: { Data: 'supply_order', Condition: `Supply_Order_SerialNumber='${applyId}'` },
                    type: 'GET'
                });
                const orders = Array.isArray(orderRes) ? orderRes : (orderRes.Data || []);
                this.list = orders;
                if (!orders || orders.length === 0) { return; }

                // 批量查询拒绝记录并挂载到每条订单
                const ids = (this.list || []).map(i => i.Supply_Order_SerialNumber).filter(Boolean);
                if (ids.length > 0) {
                    try {
                        const logs = await httpRequest({
                            url: '/generalBusiness/generalQueryByTableName',
                            data: {
                                Data: 'supply_order_examine_log',
                                Condition: `Supply_Order_SerialNumber IN (${ids.map(id => `'${id}'`).join(',')})`
                            },
                            type: 'GET'
                        });
                        const arr = Array.isArray(logs) ? logs : (logs.Data || []);
                        const map = {};
                        arr.forEach(l => {
                            const k = l.Supply_Order_SerialNumber;
                            if (!map[k]) map[k] = [];
                            map[k].push(l);
                        });
                        this.list = this.list.map(row => ({
                            ...row,
                            examineLogs: map[row.Supply_Order_SerialNumber] || []
                        }));
                    } catch (e) {
                        // 查询日志失败不影响详情展示
                    }
                }

                // 2) 查询原供应单信息（根据订单上的报价编号）
                const unitPriceId = orders[0].Supply_Unit_Price_SerialNumber || '';
                // 记录当前报价编号，便于顶部展示原信息
                this.currentSupplyId = unitPriceId;
                if (unitPriceId) {
                    const supRes = await httpRequest({
                        url: '/generalBusiness/generalQueryByTableName',
                        data: { Data: 'supply_unitprice', Condition: `Supply_Unit_Price_SerialNumber='${unitPriceId}'` },
                        type: 'GET'
                    });
                    const supArr = Array.isArray(supRes) ? supRes : (supRes.Data || []);
                    this.pageSupply = supArr && supArr[0] ? supArr[0] : null;

                    // 3) 直接查询并展示阶段模板（按报价编号），不做排序
                    try {
                        const safeId = String(unitPriceId || '').replace(/'/g, "''");
                        const stagedRes = await httpRequest({
                            url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                            data: { Data: 'supply_unitprice_staged_payment', Condition: `Supply_Unit_Price_SerialNumber='${safeId}'` }
                        });
                        this.stagedPayments = Array.isArray(stagedRes) ? stagedRes : (stagedRes.Data || []);
                    } catch (e) { this.stagedPayments = []; }
                }
            } catch (e) {
                this.$message && this.$message.error && this.$message.error('查询失败，请稍后再试');
            }
        },
        // 操作按钮可见性：仅从销售订单入口（带 applyId）显示，且订单为待处理状态
        canOperate(row) {
            const isFromSalesOrder = !!this.fromApplyDetail; // sales_order/index.js 跳转携带 applyId
            const isPending = String(row && row.Row_Status) === '0';
            return isFromSalesOrder && isPending;
        },
        // 通过：将订单状态置为 2（已通过），并按报价阶段初始化订单阶段付款（若尚未存在）
        acceptOrder(row) {
            try {
                const tableName = 'supply_order';
                const primaryKey = 'Supply_Order_SerialNumber';
                const id = row && row[primaryKey];
                if (!id) { this.$message && this.$message.error && this.$message.error('未获取到订单编号'); return; }
                if (!this.fromApplyDetail) { this.$message && this.$message.error && this.$message.error('仅销售订单入口可操作'); return; }

                httpRequest({
                    url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                    data: { Data: tableName, Condition: `${primaryKey}='${id}'` }
                }).then(async data => {
                    if (!Array.isArray(data) || data.length !== 1) { this.$message.error('订单不存在或存在重复记录'); return; }
                    data[0].Row_Status = '2';
                    const orderAmount = Number((data[0] && data[0].Amount) || row.Amount || 0);
                    // 设置供货订单未付款、未收款 = 订单金额；未发货、未收货 = 交易数量
                    const amtStr = String((data[0].Amount !== undefined && data[0].Amount !== null) ? data[0].Amount : (row.Amount || ''));
                    data[0].Remain_Amount = amtStr; // 未付款金额
                    data[0].Unamount = amtStr;      // 未收款金额

                    const qtyStr = String((data[0].Quantity !== undefined && data[0].Quantity !== null) ? data[0].Quantity : (row.Quantity || ''));
                    data[0].Undelivery_Quantity = qtyStr; // 未发货数量
                    data[0].Unreceipt_Quantity = qtyStr;   // 未收货数量
                    const unitPriceId = row.Supply_Unit_Price_SerialNumber || data[0].Supply_Unit_Price_SerialNumber || '';

                    // 若尚未有阶段付款明细，则按报价阶段初始化
                    let paystagesToAdd = [];
                    try {
                        const existed = await httpRequest({
                            url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                            data: { Data: 'supply_order_paystages', Condition: `Supply_Order_SerialNumber='${row.Supply_Order_SerialNumber}'` },
                            type: 'POST'
                        });
                        const hasExisting = Array.isArray(existed) ? existed.length > 0 : ((existed && existed.Data) ? existed.Data.length > 0 : false);
                        if (!hasExisting && unitPriceId) {
                            const stagedRes = await httpRequest({
                                url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                                data: { Data: 'supply_unitprice_staged_payment', Condition: `Supply_Unit_Price_SerialNumber='${unitPriceId}'` },
                                type: 'POST'
                            });
                            const stagedArr = Array.isArray(stagedRes) ? stagedRes : (stagedRes && stagedRes.Data) || [];
                            paystagesToAdd = (stagedArr || []).map(sp => {
                                const percentVal = Number(sp.Percent || 0);
                                const due = Number.isFinite(orderAmount * percentVal / 100)
                                    ? Number((orderAmount * percentVal / 100).toFixed(2))
                                    : '';
                                return {
                                    Supply_Order_Paystages_SerialNumber: '',
                                    Supply_Order_SerialNumber: row.Supply_Order_SerialNumber,
                                    Supply_Unit_Price_Staged_Payment_SerialNumber: sp.Supply_Unit_Price_Staged_Payment_SerialNumber || '',
                                    Stage_Name: sp.Stage_Name || '',
                                    Percent: sp.Percent !== undefined ? sp.Percent : '',
                                    Due_Amount: due !== '' ? String(due) : '',
                                    Trading_Amount: due !== '' ? String(due) : '',
                                    Remain_Amount: due !== '' ? String(due) : '',
                                    Paid_Amount: '0',
                                    Collection_Date: '',
                                    Row_Status: '0'
                                };
                            });
                        }
                    } catch (e) { /* 初始化失败不阻塞接受逻辑 */ }

                    const lJSONObject_Modify = {}; lJSONObject_Modify[tableName] = data;
                    const lJSONObject_DataSet = { Modify: lJSONObject_Modify, Add: {} };
                    if (paystagesToAdd.length > 0) lJSONObject_DataSet.Add['supply_order_paystages'] = paystagesToAdd;
                    const Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                    lJSONObject_DataSet['Add']['base_operation_log'] = [{
                        Operation_Type: '0', Operation_Path: getRelativePath(), Operation_Description: '接受订单',
                        Operation_Main, Operation_Interface: 'generalSaveByRequestBody', Operation_IP: getIpAddress()
                    }];
                    return httpRequest({ contentType: 'JSON', url: '/generalBusiness/generalSaveByRequestBody', data: JSON.stringify({ Data: lJSONObject_DataSet }) });
                }).then(res => {
                    if (res && (res.Status === 'success')) {
                        this.$message && this.$message.success && this.$message.success('已通过');
                        this.$set && this.$set(row, 'Row_Status', '2');
                        // 成功后返回来源页面
                        this.handleBack();
                    }
                    else if (res) { this.$message && this.$message.error && this.$message.error(res.Message || '保存失败'); }
                }).catch(() => this.$message && this.$message.error && this.$message.error('系统错误，请联系开发者!'));
            } catch (e) { console.error(e); this.$message && this.$message.error && this.$message.error('系统错误，请联系开发者!'); }
        },
        // 拒绝：将订单状态置为 3，并记录拒绝原因，同时回滚报价的已售量与剩余量
        rejectOrder(row) {
            this.$prompt && this.$prompt('请输入拒绝原因', '拒绝订单', { confirmButtonText: '确定', cancelButtonText: '取消', inputPattern: /.+/, inputErrorMessage: '拒绝原因不能为空' })
                .then(({ value }) => {
                    const reason = value || '';
                    try {
                        const tableName = 'supply_order';
                        const primaryKey = 'Supply_Order_SerialNumber';
                        const id = row && row[primaryKey];
                        const unitPriceId = row.Supply_Unit_Price_SerialNumber;
                        if (!id) { this.$message && this.$message.error && this.$message.error('未获取到订单编号'); return; }
                        if (!this.fromApplyDetail) { this.$message && this.$message.error && this.$message.error('仅销售订单入口可操作'); return; }

                        // 1) 查询订单原始数据
                        httpRequest({ url: '/generalBusiness/generalQueryByTableNameWithOriginal', data: { Data: tableName, Condition: `${primaryKey}='${id}'` } })
                            .then(data => {
                                if (!Array.isArray(data) || data.length !== 1) { this.$message.error('订单不存在或存在重复记录'); return Promise.reject('invalid_order'); }
                                data[0].Row_Status = '3';

                                // 2) 查询对应报价，准备回滚已售量/剩余量
                                if (!unitPriceId) { // 若缺少报价编号，仍允许拒绝但不做数量回滚
                                    const lJSONObject_Modify = {}; lJSONObject_Modify[tableName] = data;
                                    const lJSONObject_DataSet = {
                                        Modify: lJSONObject_Modify,
                                        Add: {
                                            supply_order_examine_log: [{ Supply_Order_SerialNumber: id, Reason: reason, Operation_ID: getCookie('user') || '' }],
                                            base_operation_log: [{ Operation_Type: '0', Operation_Path: getRelativePath(), Operation_Description: '拒绝订单', Operation_Main: JSON.stringify(deepClone(lJSONObject_Modify)), Operation_Interface: 'generalSaveByRequestBody', Operation_IP: getIpAddress() }]
                                        }
                                    };
                                    return httpRequest({ contentType: 'JSON', url: '/generalBusiness/generalSaveByRequestBody', data: JSON.stringify({ Data: lJSONObject_DataSet }) });
                                }

                                return httpRequest({ url: '/generalBusiness/generalQueryByTableNameWithOriginal', data: { Data: 'supply_unitprice', Condition: `Supply_Unit_Price_SerialNumber='${unitPriceId}'` } })
                                    .then(supArr => {
                                        let lJSONObject_Modify = {}; lJSONObject_Modify[tableName] = data;
                                        const toNum = (v) => {
                                            const n = Number(String(v).replace(/[^0-9.\-]/g, ''));
                                            return Number.isFinite(n) ? n : 0;
                                        };
                                        const qty = toNum(row.Quantity || 0);
                                        if (Array.isArray(supArr) && supArr.length === 1) {
                                            const sup = supArr[0];
                                            const sales = toNum(sup.Sales_Quantity || 0);
                                            const remain = toNum(sup.Remain_Quantity || 0);
                                            const newSold = accSub(sales, qty);
                                            const newRemain = accAdd(remain, qty);
                                            sup.Sales_Quantity = String(newSold >= 0 ? newSold : 0);
                                            sup.Remain_Quantity = String(newRemain);
                                            lJSONObject_Modify['supply_unitprice'] = [sup];
                                        }

                                        const lJSONObject_DataSet = {
                                            Modify: lJSONObject_Modify,
                                            Add: {
                                                supply_order_examine_log: [{ Supply_Order_SerialNumber: id, Reason: reason, Operation_ID: getCookie('user') || '' }],
                                                base_operation_log: [{ Operation_Type: '0', Operation_Path: getRelativePath(), Operation_Description: '拒绝订单（含数量回滚）', Operation_Main: JSON.stringify(deepClone(lJSONObject_Modify)), Operation_Interface: 'generalSaveByRequestBody', Operation_IP: getIpAddress() }]
                                            }
                                        };
                                        return httpRequest({ contentType: 'JSON', url: '/generalBusiness/generalSaveByRequestBody', data: JSON.stringify({ Data: lJSONObject_DataSet }) });
                                    });
                            }).then(res => {
                                if (res && (res.Status === 'success')) {
                                    this.$message && this.$message.success && this.$message.success('已拒绝');
                                    this.$set && this.$set(row, 'Row_Status', '3');
                                    // 成功后返回来源页面
                                    this.handleBack();
                                }
                                else if (res) { this.$message && this.$message.error && this.$message.error(res.Message || '保存失败'); }
                            }).catch(() => this.$message && this.$message.error && this.$message.error('系统错误，请联系开发者!'));
                    } catch (e) { console.error(e); this.$message && this.$message.error && this.$message.error('系统错误，请联系开发者!'); }
                })
                .catch(() => { /* 取消输入 */ });
        }
    }
});
